<template>
  <el-dialog
    title="添加资源"
    :visible.sync="isShowCreateSource"
    width="65%"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    >
    <div class="course-form">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="资源名称" prop="fileName">
          <el-input style="width: 50%" v-model="ruleForm.fileName" placeholder="请输入资源名称" />
        </el-form-item>
        <el-form-item label="资源类型" prop="type">
          <el-radio-group :disabled="!!ruleForm.src" v-model="ruleForm.type">
            <el-radio :label="1">视频</el-radio>
            <el-radio :label="0">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资源" prop="src">
          <el-upload
            class="upload-demo"
            drag
            v-bind:on-progress="uploadVideoProcess"
            v-loading="loading"
            :on-success="picUpload"
            :before-upload="beforeUpload"
            :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
            name="file"
            :disabled="!ruleForm.type && !(ruleForm.type === 0 ? true : false)"
            :headers="{
              'access-token': $store.state.user.TOKEN,
            }"
            multiple
          >
            <div v-if="!ruleForm.src && !videoFlag">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </div>
            <img
              style="
                width: auto;
                height: auto;
                max-height: 100%;
                max-width: 100%;
              "
              v-if="ruleForm.src && ruleForm.type === 0"
              :src="$store.state.user.BASE_URL + ruleForm.src"
              alt=""
            />
            <video
              style="
                width: auto;
                height: auto;
                max-height: 100%;
                max-width: 100%;
              "
              v-if="ruleForm.src && ruleForm.type === 1"
              :src="$store.state.user.BASE_URL + ruleForm.src"
              alt=""
            />
            <el-progress
              v-if="ruleForm.type === 1 && videoFlag"
              type="circle"
              v-bind:percentage="videoUploadPercent"
            ></el-progress>
            <div class="el-upload__tip" slot="tip">
            </div>
          </el-upload>

        </el-form-item>
        <el-form-item label="资源分类" prop="resourceClassification">
          <el-radio-group v-model="ruleForm.resourceClassification">
            <el-radio :label="0">教学视频</el-radio>
            <el-radio :label="1">课上小游戏</el-radio>
            <el-radio :label="3">其他</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>


    <span slot="footer" class="dialog-footer">
    <el-button size="small" @click="close">取 消</el-button>
    <el-button v-loading="buttonLoading" size="small" @click="submitForm('ruleForm')" type="primary">确 定</el-button>
  </span>
  </el-dialog>

</template>

<script>

import {createSchoolSource} from "@/api/schoolSource";


export default {
  name: "incrementCourse",
  props:{
    isShowCreateSource:{
      type:Boolean
    }
  },
  data() {
    return {
      ruleForm: {
        teacherId:this.$store.state.user.USER_INFO.id,
        src:"",
        resourceClassification: "",
        fileName:"",
        type:"",
        schoolId: this.$store.state.user.USER_INFO.pscShId
      },
      videoUploadPercent: "",
      videoFlag: false,
      buttonLoading:false,
      loading:false,
      rules: {
        fileName: [
          { required: true, message: '请输入资源名称', trigger: 'blur' },
        ],
        resourceClassification:[
          { required: true, message: '请选择资源分类', trigger: 'change' },
        ],
        type:[
          { required: true, message: '请选择资源类型', trigger: 'blur' },
        ],
        src:[
          { required: true, message: '请上传资源', trigger: 'blur' },
        ]
      }
    };
  },
  created() {
  },
  methods:{
    uploadVideoProcess(event, file, fileList) {
      //注意在data中添加对应的变量名
      console.log(event,"event",file,"file")
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    close(){
      this.$emit("close",false)
    },
    validator() {
      this.$refs.ruleForm.validate(() => {});
    },
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      const typesVideo = ["mp4","webm"];
      if(this.ruleForm.type == 1){
        this.videoFlag = true;
        if (!typesVideo.includes(fileSuffix)) {
          this.videoFlag = false
          this.$message.error(`文件只能是 ${typesVideo.join()} 格式!`);
        }
        return typesVideo.includes(fileSuffix);
      }else{
        this.loading = true
        if (!types.includes(fileSuffix)) {
          this.$message.error(`文件只能是 ${types.join()} 格式!`);
          this.loading = false;
        }
        return types.includes(fileSuffix);
      }
    },

    picUpload(e) {
      if (e.code === 200) {
        this.ruleForm.src = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      if(this.ruleForm.type == 1){
        this.videoFlag = false;
      }else{
        this.loading = false;
      }
      this.validator();
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          console.log(this.ruleForm);
          createSchoolSource(this.ruleForm).then(response=>{
            this.buttonLoading = false
            if(response.code == 200){
              this.$message.success("保存成功");
              this.$emit("addList",[response.result]);
              this.close();
            }else{
              this.$message.error(response.message);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input__inner {
  text-align: left !important;
}
.course-form {
  background: #fff;
  padding: 0vh 10vw 0;
::v-deep .el-radio {
  margin: 10px;
}
.source {
  display: flex;
  flex-direction: column;
.top-source {
  display: flex;
.source-my {
  font-size: .8vw;
  color: #1677FF;
  cursor: pointer;
}
.source-school {
  font-size: .8vw;
  color: #1677FF;
  margin-left: 2vw;
  cursor: pointer;
}
}
.source-val {
  display: flex;
  width: 80%;
  align-items: center;
  padding: .5vh .5vw;
  background: #ECF4FF;
.val-icon {
  color: #1677FF;
i{
  font-size: 1.3vw;
}
}
.val-text {
  color: #666666;
  margin-left: .2vw;
  font-size: .8vw;
}
.val-del {
  color: #FF6162;
  margin-left: 10vw;
  font-size: .7vw;
}
}
}
}
::v-deep .el-upload-list__item {
  display: none;
}

</style>
